//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.yuan.java.aliyunapi;


import javax.net.ssl.*;
import java.io.*;
import java.net.*;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.zip.GZIPInputStream;

public class WebUtils {
    private static final String METHOD_LIST = "LIST";
    private static final String METHOD_POST = "POST";
    private static final String METHOD_GET = "GET";

    public WebUtils() {
    }

    public static ResData _doGetAsByte(ShowapiRequest req) throws IOException {
        HttpURLConnection conn = null;
        byte[] rsp = null;
        ResData res = new ResData();

        try {
            String ctype = "application/x-www-form-urlencoded;charset=" + req.getCharset();
            String query = buildQuery(req.getTextMap(), req.getCharset());

            try {
                conn = getConnection(buildGetUrl(req.getUrl(), query), "GET", ctype, req.getHeadMap(), req.getProxy(), req.isAllowRedirect());
                conn.setConnectTimeout(req.getConnectTimeout());
                conn.setReadTimeout(req.getReadTimeout());
            } catch (IOException var12) {
                ShowApiLogger.logCommError(var12, req.getUrl(), (String) req.getTextMap().get("showapi_app_id"), req.getTextMap());
                throw var12;
            }

            try {
                Map res_headMap = conn.getHeaderFields();
                rsp = getResponseAsByte(conn);
                req.setRes_headMap(res_headMap);
            } catch (IOException var11) {
                ShowApiLogger.logCommError(var11, req.getUrl(), (String) req.getTextMap().get("showapi_app_id"), req.getTextMap());
                throw var11;
            }
        } finally {
            if (conn != null) {
                conn.disconnect();
            }

        }

        res.setResData(rsp);
        res.setRes_maybe_encoding(getResponseCharset(conn.getContentType()));
        return res;
    }

    public static ResData _doPostAsByte(ShowapiRequest req) throws IOException {
        String ctype = "application/x-www-form-urlencoded;charset=" + req.getCharset();
        String query = buildQuery(req.getTextMap(), req.getCharset());
        ResData res = new ResData();
        byte[] content = null;
        if (query != null) {
            content = query.getBytes(req.getCharset());
        } else {
            content = "".getBytes(req.getCharset());
        }

        HttpURLConnection conn = null;
        OutputStream out = null;
        Object var7 = null;

        byte[] rsp;
        try {
            conn = getConnection(new URL(req.getUrl()), "POST", ctype, req.getHeadMap(), req.getProxy(), req.isAllowRedirect());
            conn.setConnectTimeout(req.getConnectTimeout());
            conn.setReadTimeout(req.getReadTimeout());
            out = conn.getOutputStream();
            out.write(content);
            Map res_headMap = conn.getHeaderFields();
            rsp = getResponseAsByte(conn);
            req.setRes_headMap(res_headMap);
        } catch (IOException var12) {
            ShowApiLogger.logCommError(var12, req.getUrl(), (String) req.getTextMap().get("showapi_app_id"), query);
            throw var12;
        } finally {
            if (out != null) {
                out.close();
            }

            if (conn != null) {
                conn.disconnect();
            }

        }

        res.setResData(rsp);
        res.setRes_maybe_encoding(getResponseCharset(conn.getContentType()));
        return res;
    }

    private static ResData _doPostWithFileAsByte(ShowapiRequest req) throws IOException {
        String boundary = String.valueOf(System.nanoTime());
        HttpURLConnection conn = null;
        OutputStream out = null;
        byte[] rsp = null;
        ResData res = new ResData();

        try {
            StringBuilder strBody = new StringBuilder();

            try {
                String ctype = "multipart/form-data;charset=" + req.getCharset() + ";boundary=" + boundary;
                conn = getConnection(new URL(req.getUrl()), "POST", ctype, req.getHeadMap(), req.getProxy(), req.isAllowRedirect());
                conn.setConnectTimeout(req.getConnectTimeout());
                conn.setReadTimeout(req.getReadTimeout());
                out = conn.getOutputStream();
                byte[] entryBoundaryBytes = ("\r\n--" + boundary + "\r\n").getBytes(req.getCharset());
                Set<Entry<String, String>> textEntrySet = req.getTextMap().entrySet();
                Iterator var11 = textEntrySet.iterator();

                while (true) {
                    if (!var11.hasNext()) {
                        Set<Entry<String, File>> fileEntrySet = req.getUploadMap().entrySet();
                        Iterator var25 = fileEntrySet.iterator();

                        while (var25.hasNext()) {
                            Entry<String, File> fileEntry = (Entry) var25.next();
                            File f = (File) fileEntry.getValue();
                            FileItem fileItem = new FileItem(f);
                            if (fileItem.getContent() != null) {
                                byte[] fileBytes = getFileEntry((String) fileEntry.getKey(), fileItem.getFileName(), fileItem.getMimeType(), req.getCharset());
                                out.write(entryBoundaryBytes);
                                out.write(fileBytes);
                                out.write(fileItem.getContent());
                            }
                        }

                        byte[] endBoundaryBytes = ("\r\n--" + boundary + "--\r\n").getBytes(req.getCharset());
                        out.write(endBoundaryBytes);
                        Map res_headMap = conn.getHeaderFields();
                        rsp = getResponseAsByte(conn);
                        req.setRes_headMap(res_headMap);
                        break;
                    }

                    Entry<String, String> textEntry = (Entry) var11.next();
                    strBody.append((String) textEntry.getKey() + "=" + (String) textEntry.getValue() + "&");
                    byte[] textBytes = getTextEntry((String) textEntry.getKey(), (String) textEntry.getValue(), req.getCharset());
                    out.write(entryBoundaryBytes);
                    out.write(textBytes);
                }
            } catch (IOException var19) {
                ShowApiLogger.logCommError(var19, req.getUrl(), (String) req.getTextMap().get("showapi_app_id"), strBody.toString());
                throw var19;
            }
        } finally {
            if (out != null) {
                out.close();
            }

            if (conn != null) {
                conn.disconnect();
            }

        }

        res.setResData(rsp);
        res.setRes_maybe_encoding(getResponseCharset(conn.getContentType()));
        return res;
    }

    public static String doPost(ShowapiRequest req) throws IOException {
        ResData res;
        if (req.getUploadMap() != null && !req.getUploadMap().isEmpty()) {
            res = _doPostWithFileAsByte(req);
        } else {
            res = _doPostAsByte(req);
        }

        return new String(res.getResData(), res.getRes_maybe_encoding());
    }

    public static byte[] doPostAsByte(ShowapiRequest req) throws IOException {
        return req.getUploadMap() != null && !req.getUploadMap().isEmpty() ? _doPostWithFileAsByte(req).getResData() : _doPostAsByte(req).getResData();
    }

    public static String doGet(ShowapiRequest req) throws IOException {
        ResData res = _doGetAsByte(req);
        return new String(res.getResData(), res.getRes_maybe_encoding());
    }

    public static byte[] doGetAsByte(ShowapiRequest req) throws IOException {
        ResData res = _doGetAsByte(req);
        return res.getResData();
    }

    public static ByteArrayOutputStream unzip(InputStream in) {
        ByteArrayOutputStream fout = new ByteArrayOutputStream();

        try {
            GZIPInputStream gzin = new GZIPInputStream(in);
            byte[] buf = new byte[1024];

            int num;
            while ((num = gzin.read(buf, 0, buf.length)) != -1) {
                fout.write(buf, 0, num);
            }

            gzin.close();
            fout.close();
            in.close();
        } catch (Exception var5) {
            System.out.println(var5);
        }

        return fout;
    }

    private static byte[] getTextEntry(String fieldName, String fieldValue, String charset) throws IOException {
        StringBuilder entry = new StringBuilder();
        entry.append("Content-Disposition:form-data; name=\"");
        entry.append(fieldName);
        entry.append("\"\r\nContent-Type:text/plain\r\n\r\n");
        entry.append(fieldValue);
        return entry.toString().getBytes(charset);
    }

    private static byte[] getFileEntry(String fieldName, String fileName, String mimeType, String charset) throws IOException {
        StringBuilder entry = new StringBuilder();
        entry.append("Content-Disposition:form-data; name=\"");
        entry.append(fieldName);
        entry.append("\"; filename=\"");
        entry.append(fileName);
        entry.append("\"\r\nContent-Type:");
        entry.append(mimeType);
        entry.append("\r\n\r\n");
        return entry.toString().getBytes(charset);
    }

    private static HttpURLConnection getConnection(URL url, String method, String ctype, Map<String, String> headerMap, Proxy proxy, boolean allowRedirect) throws IOException {
        Object conn;
        if (proxy != null) {
            conn = (HttpURLConnection) url.openConnection(proxy);
        } else {
            conn = (HttpURLConnection) url.openConnection();
        }

        if (conn instanceof HttpsURLConnection) {
            HttpsURLConnection connHttps = (HttpsURLConnection) conn;

            try {
                SSLContext ctx = SSLContext.getInstance("TLS");
                ctx.init((KeyManager[]) null, new TrustManager[]{new WebUtils.TrustAllTrustManager()}, new SecureRandom());
                connHttps.setSSLSocketFactory(ctx.getSocketFactory());
                connHttps.setHostnameVerifier(new HostnameVerifier() {
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                });
            } catch (Exception var9) {
                throw new IOException(var9);
            }

            conn = connHttps;
        }

        ((HttpURLConnection) conn).setRequestMethod(method);
        ((HttpURLConnection) conn).setDoInput(true);
        if (method.equals("POST")) {
            ((HttpURLConnection) conn).setDoOutput(true);
        }

        ((HttpURLConnection) conn).setRequestProperty("Accept", "application/json, text/javascript, */*; ");
        ((HttpURLConnection) conn).setRequestProperty("User-Agent", "showapi-sdk-java");
        ((HttpURLConnection) conn).setRequestProperty("Content-Type", ctype);
        if (headerMap != null) {
            Iterator var11 = headerMap.entrySet().iterator();

            while (var11.hasNext()) {
                Entry<String, String> entry = (Entry) var11.next();
                ((HttpURLConnection) conn).setRequestProperty((String) entry.getKey(), (String) entry.getValue());
            }
        }

        ((HttpURLConnection) conn).setInstanceFollowRedirects(allowRedirect);
        return (HttpURLConnection) conn;
    }

    private static URL buildGetUrl(String strUrl, String query) throws IOException {
        URL url = new URL(strUrl);
        if (StringUtils.isEmpty(query)) {
            return url;
        } else {
            if (StringUtils.isEmpty(url.getQuery())) {
                if (strUrl.endsWith("?")) {
                    strUrl = strUrl + query;
                } else {
                    strUrl = strUrl + "?" + query;
                }
            } else if (strUrl.endsWith("&")) {
                strUrl = strUrl + query;
            } else {
                strUrl = strUrl + "&" + query;
            }

            return new URL(strUrl);
        }
    }

    public static String buildQuery(Map params, String charset) {
        if (params != null && !params.isEmpty()) {
            StringBuilder query = new StringBuilder();
            Set<Entry<String, String>> entries = params.entrySet();
            boolean hasParam = false;

            try {
                Iterator var6 = entries.iterator();

                while (var6.hasNext()) {
                    Entry<String, String> entry = (Entry) var6.next();
                    String name = (String) entry.getKey();
                    String value = (String) entry.getValue();
                    if (name != null && name.length() > 0 && value != null) {
                        if (hasParam) {
                            query.append("&");
                        } else {
                            hasParam = true;
                        }

                        query.append(name).append("=").append(URLEncoder.encode(value, charset));
                    }
                }
            } catch (Exception var9) {
                var9.printStackTrace();
            }

            return query.toString();
        } else {
            return null;
        }
    }

    protected static byte[] getResponseAsByte(HttpURLConnection conn) throws IOException {
        InputStream es = conn.getErrorStream();
        if (es == null) {
            if (conn.getContentEncoding() != null && conn.getContentEncoding().toLowerCase().equals("gzip")) {
                byte[] bbb = unzip(conn.getInputStream()).toByteArray();
                return bbb;
            } else {
                return conn.getResponseCode() >= 400 ? new byte[0] : readByteFromStream(conn.getInputStream());
            }
        } else {
            String charset_res = getResponseCharset(conn.getContentType());
            byte[] b = readByteFromStream(conn.getErrorStream());
            String msg = new String(b, charset_res);
            if (StringUtils.isEmpty(msg)) {
                throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
            } else if (conn.getResponseCode() == 555) {
                return b;
            } else {
                throw new IOException(msg);
            }
        }
    }

    protected static String getResponseAsString(HttpURLConnection conn) throws IOException {
        String charset_res = getResponseCharset(conn.getContentType());
        InputStream es = conn.getErrorStream();
        if (es == null) {
            if (conn.getContentEncoding() != null && conn.getContentEncoding().toLowerCase().equals("gzip")) {
                byte[] bbb = unzip(conn.getInputStream()).toByteArray();
                return new String(bbb, charset_res);
            } else {
                return _readCharString(conn.getInputStream(), charset_res);
            }
        } else {
            String msg = _readCharString(es, charset_res);
            if (StringUtils.isEmpty(msg)) {
                throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
            } else {
                throw new IOException(msg);
            }
        }
    }

    public static byte[] readByteFromStream(InputStream stream) throws IOException {
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            boolean var3 = false;

            int read;
            while ((read = stream.read(buf)) > 0) {
                out.write(buf, 0, read);
            }

            byte[] var5 = out.toByteArray();
            return var5;
        } finally {
            if (stream != null) {
                stream.close();
            }

        }
    }

    private static String _readCharString(InputStream stream, String charset) throws IOException {
        try {
            Reader reader = new InputStreamReader(stream, charset);
            StringBuilder response = new StringBuilder();
            char[] buff = new char[1024];
            boolean var5 = false;

            int read;
            while ((read = reader.read(buff)) > 0) {
                response.append(buff, 0, read);
            }

            String var7 = response.toString();
            return var7;
        } finally {
            if (stream != null) {
                stream.close();
            }

        }
    }

    private static String getResponseCharset(String ctype) {
        String charset = "utf-8";
        if (!StringUtils.isEmpty(ctype)) {
            String[] params = ctype.split(";");
            String[] var6 = params;
            int var5 = params.length;

            for (int var4 = 0; var4 < var5; ++var4) {
                String param = var6[var4];
                param = param.trim();
                if (param.startsWith("charset")) {
                    String[] pair = param.split("=", 2);
                    if (pair.length == 2 && !StringUtils.isEmpty(pair[1])) {
                        charset = pair[1].trim();
                    }
                    break;
                }
            }
        }

        return charset;
    }

    public static String decode(String value, String charset) {
        String result = null;
        if (!StringUtils.isEmpty(value)) {
            try {
                result = URLDecoder.decode(value, charset);
            } catch (IOException var4) {
                throw new RuntimeException(var4);
            }
        }

        return result;
    }

    public static String encode(String value, String charset) {
        String result = null;
        if (!StringUtils.isEmpty(value)) {
            try {
                result = URLEncoder.encode(value, charset);
            } catch (IOException var4) {
                throw new RuntimeException(var4);
            }
        }

        return result;
    }

    private static Map<String, String> getParamsFromUrl(String url) {
        Map<String, String> map = null;
        if (url != null && url.indexOf(63) != -1) {
            map = splitUrlQuery(url.substring(url.indexOf(63) + 1));
        }

        if (map == null) {
            map = new HashMap();
        }

        return (Map) map;
    }

    public static Map<String, String> splitUrlQuery(String query) {
        Map<String, String> result = new HashMap();
        String[] pairs = query.split("&");
        if (pairs != null && pairs.length > 0) {
            String[] var6 = pairs;
            int var5 = pairs.length;

            for (int var4 = 0; var4 < var5; ++var4) {
                String pair = var6[var4];
                String[] param = pair.split("=", 2);
                if (param != null && param.length == 2) {
                    result.put(param[0], param[1]);
                }
            }
        }

        return result;
    }


    public static class TrustAllTrustManager implements X509TrustManager {
        public TrustAllTrustManager() {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    }

    public static class VerisignTrustManager implements X509TrustManager {
        public VerisignTrustManager() {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    }
}
